package com.faceye.core.repository.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 构建DataSource
 */
@Slf4j
public class DataSourceBuilder {

    /**
     *
     * @param props,遵循druid 规范
     * @return
     */
    public static DataSource builder(Map<String,String> props){
        return init(props);
    }

    /**
     * 简单构建遵循druid规范的props.
     * @param url
     * @param username
     * @param password
     * @return
     */
    public static Map<String,String> buildDruidDataSourceProps(String url,String username,String password){
        Map<String,String> props=new HashMap();
        props.put("url",url);
        props.put("username",username);
        props.put("password",password);
//        props.put("driverClassName","com.mysql.jdbc.Driver");
        props.put("driverClassName","com.mysql.cj.jdbc.Driver");
        props.put("initialSize","3");

        props.put("type","com.alibaba.druid.pool.DruidDataSource");
        props.put("minIdle","6");
        props.put("maxActive","20");
        props.put("maxWait","120000");
        return props;
    }

    private static DataSource init(Map props){
        DataSource dataSource=null;
        try {
            dataSource = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            log.error(">>DruidDataSourceFactory.createDataSource error:{}",e);
        }
        return dataSource;
    }
}
